package com.dingyx.ps.repository;

import cn.hutool.core.exceptions.ExceptionUtil;
import com.alibaba.fastjson.JSONObject;
import com.dingyx.ps.redis.RedisTemplateDao;
import com.dingyx.ps.model.vo.AccountVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author dingyuxin
 */
@Slf4j
@Repository
public class UserCacheRepository extends RedisTemplateDao {


    /**
     * 删除对象 ,依赖key
     */
    public void delete(String key) {
        List<String> list = new ArrayList<String>();
        list.add(key);
        delete(list);
    }

    /**
     * 删除集合 ,依赖key集合
     */
    public void delete(List<String> keys) {
        redisTemplate.delete(keys);
    }

    public void cacheUserInfo(String key, Object bossUser, Long expireTime){
        String tmp = JSONObject.toJSONString(bossUser);
        getValue().set(key, tmp, expireTime, TimeUnit.SECONDS);
    }

    public String getUserInfo(String key){
        return getValue().get(key);
    }

    public AccountVO getUserObject(String key){
        AccountVO accountVO = null;
        try {
            String userInfo = getValue().get(key);
            accountVO = JSONObject.parseObject(userInfo, AccountVO.class);
        }catch(Exception e){
            log.error(ExceptionUtil.getMessage(e));
        }
        return accountVO;
    }

    public void cacheUserInfo(String key, String value, Long expireTime){
        getValue().set(key, value, expireTime, TimeUnit.SECONDS);
    }

    public <T> T get(String key, Class<T> t){
        String tmp = getValue().get(key);
        if(StringUtils.isNotBlank(tmp)){
            return JSONObject.parseObject(tmp, t);
        }
        return null;
    }

    public void expire(String s, Long sessionKeyUserExpire) {
       expire(s, sessionKeyUserExpire, TimeUnit.SECONDS);
    }
}
